<?php

	// add a player to a roster
	session_start();
	
	// check for login
	if(!isset($_SESSION['atbat']) && !isset($_COOKIE['remember_atbat'])) {
	
		// no login, move to index page
		header("Location: http://localhost/atbat/html/");
	
	}
	
	// connect to db
	require_once '../db/db.php';
	
	$error = false;
	
	if(isset($_POST['add2roster'])) {
	
		// validate and sanitize
		if(filter_var($_POST['id'], FILTER_VALIDATE_INT)) {
		
			$id = filter_var($_POST['id'], FILTER_SANITIZE_NUMBER_INT);
		
		}else{
		
			$message[] = '<p class="error">Could not validate player id.</p>';
			$error = true;
		
		}
		
		if(filter_var($_POST['roster_id'], FILTER_VALIDATE_INT)) {
		
			$roster = filter_var($_POST['roster_id'], FILTER_SANITIZE_NUMBER_INT);
		
		}else{
		
			$message[] = '<p class="error">Could not validate roster id.</p>';
			$error = true;
		
		}
		
		// add player to roster
		if($error == false) {
		
			$sql = "INSERT INTO rosters_players (roster_id, player_id) VALUES (" . $roster . ", " . $id . ")";
			if($db->exec($sql) == 1) {
				
				// get player details
				$sql = "SELECT players.player_id, players.number, players.name, positions.code FROM players LEFT JOIN positions ON positions.position_id = players.position WHERE players.player_id = " . $id;
				$p = $db->query($sql)->fetch(PDO::FETCH_ASSOC);
				
				$message[] = '<tr id="' . $p['player_id'] . '" class="player"><td><a href="view-player/' . $p['player_id'] . '">' . $p['name'] . '</a></td><td>' . $p['number'] . '</td><td>' . $p['code'] . '</td><td><a href="edit-player/' . $p['player_id'] . '" title="Use this to change a player from one roster to another">Edit</a> | <a href="remove-player/' . $p['player_id'] . '" class="remove">Remove from Roster</a> | <a href="delete-player/' . $p['player_id'] . '" class="delete">Delete</a></td></tr>';
			
			}else{
			
				$message[] = '<p class="error">Failed to add player to roster.</p>';
				$error = true;
			
			}
			
		}
	
	}
	
	if(isset($message)) foreach($message as $m) print $m;

?>